package com.tarena.lbs.gateway.filters;

import com.alibaba.nacos.common.utils.StringUtils;
import com.tarena.lbs.common.encoder.JwtEncoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import com.tarena.lbs.common.principle.UserPrinciple;
import com.tarena.lbs.common.enums.Roles;;
@Component
@Slf4j
public class UserInfoGlobalFilter implements GlobalFilter, Ordered {

    // 使用 final 确保依赖不可变
    private final JwtEncoder<UserPrinciple> jwtEncoder;

    // 构造函数 - Spring会自动注入 JwtEncoder
    public UserInfoGlobalFilter(JwtEncoder<UserPrinciple> jwtEncoder) {
        this.jwtEncoder = jwtEncoder;  // 将注入的依赖赋值给字段
        log.info("UserInfoGlobalFilter 初始化完成，JwtEncoder 已注入");
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();

        // 从Authorization头获取Token
        String authHeader = request.getHeaders().getFirst("Authorization");
        if (StringUtils.isBlank(authHeader) || !authHeader.startsWith("Bearer ")) {
            log.debug("请求头中未找到有效的Authorization信息");
            return chain.filter(exchange);
        }

        String token = authHeader.substring(7);
        log.debug("解析JWT Token: {}", token.substring(0, Math.min(20, token.length())) + "...");

        UserPrinciple userPrinciple = parseJwtToken(token);

        if (userPrinciple != null) {
            log.debug("JWT解析成功，用户ID: {}", userPrinciple.getId());

            // 将用户ID添加到请求头，传递给下游服务
            ServerHttpRequest mutatedRequest = request.mutate()
                    .header("X-User-Id", String.valueOf(userPrinciple.getId()))
                    .build();

            return chain.filter(exchange.mutate().request(mutatedRequest).build());
        } else {
            log.warn("JWT解析失败，Token可能无效");
        }

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return -1; // 高优先级，确保在其他过滤器之前执行
    }

    private UserPrinciple parseJwtToken(String token) {
        try {
            // 使用注入的 jwtEncoder 解析Token
            return jwtEncoder.getLoginFromToken(token, UserPrinciple.class);
        } catch (Exception e) {
            log.error("JWT解析失败: {}", e.getMessage());
            return null;
        }
    }
}